<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\ShopOrder\ShopOrderCancelAction;
use App\Admin\Actions\ShopOrder\ShopOrderConfirmDeliverAction;
use App\Admin\Actions\ShopOrder\ShopOrderDeliverAction;
use App\Admin\Actions\ShopOrder\ShopOrderEditReceiverInfoAction;
use App\Admin\Actions\ShopOrder\ShopOrderSellerRemarkAction;
use App\Admin\Actions\ShopOrder\ShopOrderSystemAction;
use App\Admin\Grid\NGrid;
use App\Admin\Service\ShopOrderService;
use App\Library\Logic\LogisticsLogic;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Show;

class ShopOrderController extends AdminController
{
    private ShopOrderService $service;

    protected $title = '订单';

    public function __construct(ShopOrderService $service)
    {
        $this->service = $service;
    }

    public function paging(Content $content): Content
    {
        return $content->title($this->title())->description($this->description['index'] ?? trans('admin.list'))
            ->body(view('order.paging', [
                'newAuth' => aesEncrypt(encodeId(Admin::user()->user_id)),
            ]));
    }

    /**
     * grid
     * @return NGrid
     */
    protected function grid(): NGrid
    {
        $this->service->grid();
        $goodsColumns = $this->goodsColumns();
        $this->service->column('orderId')->sortable();
        $this->service->column('serialNumber');
        $this->service->grid->column('user_mobile', '买家');
        $this->service->grid->column('seller_mobile', '卖家');
        //$this->service->using('plug2', __('l.whether'));
        $this->service->using('help', __('l.whether'));
        $this->service->using('status');
        $this->service->grid->column('product', '商品信息')->expand(function ($model) use ($goodsColumns) {
            return new Table(array_values($goodsColumns), $model->goods->map(function ($good) use ($goodsColumns) {
                if (!empty($good->spec_file_id)) $url = $good->spec_file_id;
                else if (!empty($good->product_file_id)) $url = $good->product_file_id;
                if (!empty($url)) $good->fileUrl = view('image', [
                    'id' => $good->id,
                    'size' => 50,
                    'image' => fileIdToUrl($url)
                ]);
                return $good->only(array_keys($goodsColumns));
            })->toArray());
        })->style('text-align:center');
        $this->service->grid->column('deliver', __('shop_order.deliver_info'))->display(function () {
            if ($this->order_is_self_pickup === 2 && $this->status_deliver === 1 && (!is_null($this->logistics))) {
                $pages = LogisticsLogic::query()->where([
                    'object_type' => 1,
                    'type' => 0,
                    'object_id' => $this->order_id
                ])->pluck('serial_number')->toArray();
                return view('order.deliver_info', [
                    'id' => $this->order_id,
                    'expressNumber' => implode(',', $pages),
                    'serialNumber' => $this->serial_number,
                    'newAuth' => aesEncrypt(encodeId(Admin::user()->user_id)),
                    'json' => $this->logistics
                ]);
            } else return '暂无物流';
        });
        //$this->service->using('orderIsSelfPickup');
        $this->service->column('payPrice,freight,couponDiscount');
        $this->service->grid->column('receiver_info', __('shop_order.receiver_info'))->display(function () {
            if ($this->order_is_self_pickup === 2 && $this->ext->status_pay === 1) {
                return view('order.receiver_info', [
                    'id' => $this->order_id,
                    'serialNumber' => $this->serial_number,
                    'orderContacts' => $this->order_contacts,
                    'orderContactsMobile' => $this->order_contacts_mobile,
                    'orderContactsAddress' => $this->order_contacts_address,
                    'userRemark' => $this->user_remark,
                ]);
            } else return null;
        });
        $this->service->grid->column('plug', __('shop_product.plug'))->using(__('l.whether'))->label(__('l.openArrLabel'));
        $this->service->grid->column('system_at', __('shop_order.systemAt'))->display(function ($column) {
            return is_null($column) ? '否' : '是';
        });
        //$this->service->using('isCart');
        $this->service->column('createdAt');
        $this->service->grid->actions(function (Actions $action) {
            $action->disableEdit();
            $action->disableDelete();
            $action->disableView(false);
            if ($action->row->ext_status === 1) $action->add(new ShopOrderCancelAction);
            else if (in_array($action->row->ext_status, [2, 3]) && (int)$action->row->order_is_self_pickup === 2) {
                $action->add(new ShopOrderDeliverAction);
            }
            $action->add(new ShopOrderEditReceiverInfoAction);
            $action->add(new ShopOrderSellerRemarkAction);
            //$confirmDiffInDays = now()->parse($action->row->deliver_at)->diffInDays() > bcdiv(__('base.confirmTtl'), __('base.daySeconds'));
            //if ($confirmDiffInDays && $action->row->status_deliver) $action->add(new ShopOrderConfirmDeliverAction);
            //$settlementDiffDays = now()->parse($action->row->confirm_at)->diffInDays() > bcdiv(__('base.settleTtl'), __('base.daySeconds'));
            //if($settlementDiffDays && $action->row->status_confirm) $action->add(new ShopOrderSettlementAction);
            if (is_null($action->row->system_at) && config('app.superId') === Admin::user()->user_id) {
                $action->add(new ShopOrderSystemAction);
            }
        });
        $this->service->grid->disableActions(false);
        Admin::js('js/jquery-ui/jquery-ui.min.js?v=' . random());
        return $this->service->grid;
    }

    /**
     * detail
     * @param mixed $id
     * @return Show
     */
    protected function detail(int $id): Show
    {
        $this->service->show($id);
        $this->service->field('orderId,serialNumber,payPrice,orderEnsurePrice');
        $this->service->using('status');
        $this->service->using('orderIsSelfPickup');
        $this->service->field($this->service->fieldArr());
        $this->service->field('orderPayCallbackJson')->unescape()->as(function ($column) {
            return view('json', ['json' => json_decode($column, true)]);
        });
//        $this->service->show->panel()
//            ->tools(function ($tools) {
//                $tools->disableEdit();
//                $tools->append('<a href="#order-deliver" class="btn btn-sm btn-default" data-toggle="modal">自定义按钮</a>');
//            });;
        return $this->service->show;
    }

    private function goodsColumns(): array
    {
        return [
            'product_id' => '商品ID',
            'fileUrl' => '图片',
            'title' => '标题',
            'spec' => '规格',
            'quantity' => '数量',
            'original_price' => '原价',
            'special_price' => '特价',
            'price' => '单价',
            'buy_will_id' => '顺手买',
        ];
    }
}
